<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/18
 * Time: 13:21
 */

namespace app\index\controller;


use app\index\model\Coupon;
use think\Db;

class Defaults extends Base
{
    //首页导航---获取一级分类
    public function  index(){
        $data = Db('fenlei')->where('pid',0)->select();
        $tile =  db('config')->where('id',1)->field('tile')->find();
        $falg = msg(1, $data,'ok');

        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg'],'tile' => $tile]);
    }
#=========================================================================

    //获取产品详情
    public function getGoodsInfo(){
        $pid = input('pid');
        $data = Db('goods')->where(['id'=>$pid])->field('*,(IFNULL(sales_coun,0) + IFNULL(fictitious_munber,0) ) as total')->find();
        $data['goods_content']=str_replace('src="', 'src="https://wukongweixiu.cn/', $data['goods_content']);
        $data['shuxing'] = $this->getshuxing($data['id']);
        $data['info'] = $this->remarke();
        $falg = msg(1, $data,'ok');
        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
    }
    //获取产品属性
    public function getshuxing($pid){
        return db('shuxing')->where('goods_id',$pid)->select();
    }
    //获取产品详情页面的上半部分描述
    public function remarke(){
        $data =  db('config')->where('id',1)->field('remke')->find();
        return $data['remke'];
    }
    //产品搜索
    public function searchgoods(){
        $where =[];
        $param  = input();
        if ( isset($param['goods_name']) && !empty($param['goods_name'])){
            $where ['goods_name'] = ['like', '%'.$param['goods_name']. '%'];
        }
        if ( isset($param['cat_id']) && !empty($param['cat_id'])){
            $where ['cat_id'] = $param['cat_id'];
        }
        $where ['is_on_sale'] = 1;
        $data = db('goods')->where($where)->field('*,(IFNULL(sales_coun,0) + IFNULL(fictitious_munber,0) ) as total')->select();
        $falg = msg(1, $data,'ok');
        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg'],'remarke'=>$this->remarke()]);
    }

    //首页全部产品
    public function getAllGodds(){
        $data = db('goods')->where('is_on_sale',1)->field('*,(IFNULL(sales_coun,0) + IFNULL(fictitious_munber,0) ) as total')->paginate(10);
        $falg = msg(1, $data,'ok');
        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
    }

    #===============================================地址增删改查
    //新增地址
    public function addrAdd(){
        $input = input();
        if(empty($input['addr_name'])){
            return json(msg(-1,[],'请填写姓名'));
        }
        if(empty($input['xiangxi'])){
            return json(msg(-1,[],'请填写详细地址'));
        }
        if(empty($input['phone']) ){
            return json(msg(-1,[],'请填写正确的手机号'));
        }

        if (!preg_match("/^1[34578]{1}\d{9}$/",$input['phone'])){
            return json(msg(-1,[],'请填写正确的手机号'));
        }



        $memberid = db('member')->where('unionid',input('uinionid'))->field('id')->find();
        unset($input['uinionid']);
        $input['memberid'] = $memberid['id'];
        if ($input['isfag'] == 1){
            db('addr')->where('memberid',$memberid['memberid'])->update(['isfag'=>2]);
        }
        if(db('addr')->insert($input)){
            return json(msg(1,[],'ok'));
        }
    }
    //修改地址默认地址
    public function edit(){
        try{

            $memberid = db('addr')->where('addr_id',input('id'))->field('memberid')->find();
            db('addr')->where('memberid',$memberid['memberid'])->update(['isfag'=>2]);
            $re = db('addr')->where('addr_id',input('id'))->update(['isfag'=>input('is_isfag')]);
            if ($re){
                return json(msg(1,[],'ok'));
            }
        }catch (\Exception $e){
            return json(msg(-1,[],$e->getMessage()));
        }
    }
    public function editaddr(){
        try{
        $input = input();
        if(empty($input['addr_name'])){
            throw new \Exception('请填写姓名');
        }
        if(empty($input['xiangxi'])){
            throw new \Exception('请填写详细地址');
        }
        if(empty($input['phone']) ){
            throw new \Exception('请填写正确的手机号');
        }

        if (!preg_match("/^1[34578]{1}\d{9}$/",$input['phone'])){
            throw new \Exception('请填写正确的手机号');
        }
        $re = db('addr')->where(['addr_id'=>input('addr_id')])->update(input());
        if ($re){
            return json(msg(1,[],'ok'));
        }
        }catch (\Exception $e){
            return json(msg(-1,[],$e->getMessage()));
        }
    }

    //查询地址列表
    public function getaddr(){

        $memberid = db('member')->where('unionid',input('unionid'))->field('id')->find();
        $data = db('addr')->alias('a')
            ->join('area b','a.sheng = b.id','LEFT')
            ->join('area c','a.shi = c.id','LEFT')
            ->join('area d','a.xian = d.id','LEFT')
            ->where('a.memberid',$memberid['id'])
            ->field('a.*,b.name as bname,c.name as cname,d.name as dname')
            ->select();

        $falg = msg(1, $data,'ok');
        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
    }

    public function getoneaddr(){
        $where= [];
       $input = input();
       if (isset($input['id']))$where['a.addr_id'] = $input['id'];
        $data = db('addr')->alias('a')
            ->join('area b','a.sheng = b.id','LEFT')
            ->join('area c','a.shi = c.id','LEFT')
            ->join('area d','a.xian = d.id','LEFT')
            ->field('a.*,b.name as bname,c.name as cname,d.name as dname')
            ->where($where)->find();
        $falg = msg(1, $data,'ok');
        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
    }

    public function deladdr(){
        $re = db('addr')->where('addr_id',input('id'))->delete();
        if ($re){
            $falg = msg(1, [],'删除成功');
            return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
        }else{
            $falg = msg(-1, [],'删除失败');
            return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
        }
    }





    public function gettle(){
        $data = db('config')->field('tile')->find(1);
        $falg = msg(1, $data,'ok');
        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
    }


    #============================小程序登录unionid openid

    public function sendCode(){
        $arr = [
            ['APPID'=>'wxe8c78509bd01413f','AppSecret'=>'1c4df27d547b3928e5394fae825c3b6b'],
            ['APPID'=>'wx13841ad017b28f4c','AppSecret'=>'8f0add293cd932d3cbecb0c58666b393'],
        ];
        $type =input('type')?input('type'):0;
        $code = input("js_code", '', 'htmlspecialchars_decode');
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$arr[$type]['APPID'].'&secret='.$arr[$type]['AppSecret'].'&js_code='.$code.'&grant_type=authorization_code';
        $arr = $this -> vegt($url);
        $userinfo = json_decode($arr,true);
        $data = db('member')->where('unionid',$userinfo['unionid'])->find();
        if($data != null){
            if (empty($data['xcxopenid'])){
                $arr1['xcxopenid']   = $userinfo['openid'];
                db('member')->where('unionid',$userinfo['unionid'])->update($arr1);
            }
            $userinfo['head']= $data['head'];
            $userinfo['userid']= $data['id'];

        }else{
//            $arr1['user_name']  = $userinfo['nickname'];
//            $arr1['head']        = $userinfo['headimgurl'];
//            $arr1['xcxopenid']   = $userinfo['openid'];
//            $arr1['unionid']    = $userinfo['unionid'];
//            $arr1['sex']         = $userinfo['sex'];
//            $arr1['pid']         = input('inviteKey');
//            $id = db('member')->insertGetId($arr1);

            $userinfo['userid']= '';
        }
        $falg = msg(1, $userinfo,'ok');
        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);


    }
    public function vegt($url)
    {
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_TIMEOUT, 300);//设置超时
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $res = curl_exec($ch);//运行curl，结果以jason形式返回
//        $data = json_decode($res,true);
        curl_close($ch);

        return $res;
    }

    public function setuserinfo(){

       $id = db('member')->insertGetId([
            'unionid'  =>   input('token'),
            'user_name'=>    input('user_name'),
            'sex'       =>    (int)input('sex'),
            'head'      =>    input("head", '', 'htmlspecialchars_decode'),
            'pid'      =>    input("inviteKey",0),
        ]);
       if ($id){
           $falg = msg(1, ['id'=>$id],'ok');
       }else{
           $falg = msg(-1, [],'失败');
       }

        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
    }

    public function getuserinfo(){
        $data = db('member')->where('id',input('id'))->find();
        $addr = db('addr')->alias('a')
            ->join('area b','a.sheng = b.id','LEFT')
            ->join('area c','a.shi = c.id','LEFT')
            ->join('area d','a.xian = d.id','LEFT')
            ->where(['a.memberid'=>input('id')])
            ->where('a.isfag',1)
            ->field('a.*,b.name as bname,c.name as cname,d.name as dname')
            ->find();
        if (!empty($addr)){
            $data['addr'] = $addr;
        }else{
            $data['addr'] = [];
        }
        $falg = msg(1,$data,'ok');
        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
    }

    public function editphone(){
        if(db('member')->where('id',input('id'))->update(['phone'=>input('phone')])){
            $falg = msg(1, [],'修改成功');
            return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
        }else{
            $falg = msg(1, [],'修改失败');
            return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
        }
    }

    #======================购物车

    public function addcar(){
            try{
                $goods =  db('goodscar')->where('goods_id',(int)input('goods_id'))->find();
                if ($goods == null){
                    $id =  db('goodscar')->insertGetId(['unionid'=>input('user_id'),'goods_id'=>input('goods_id'),'shuxing_id'=>input('shuxin_id')]);
                    if($id){
                        $falg = msg(1, [],'ok');
                    }
                }
            }catch (\Exception $e){
                $falg = msg(-1, [],$e->getMessage());
            }

        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
    }
    public function getcar(){
        $data = db('goodscar')->alias('a')
            ->join('goods b','a.goods_id = b.id','LEFT')
            ->join('shuxing c','a.shuxing_id = c.id','LEFT')
            ->where(['a.unionid'=>input('user_id')])
            ->where(['a.is_select'=>['<',2]])
            ->field('a.*,b.id as gid,b.goods_name,b.original_img,b.shop_price as price,c.price as cprice,c.name as cname,c.id as shuxing_id ')
            ->order('a.id desc')
            ->paginate(10);
        $cardata = false;
        $is_selectall = true;
        $data = $data->toArray();
        foreach ($data['data'] as $k => $v){
            if($v['is_select']){
                $cardata=true;
            }else{
                $is_selectall = false;
            }
            $data['data'][$k]['price'] = $v['cprice']>=0.01?$v['cprice']:$v['price'];
        }

        $return['data'] = $data;
        $return['cardata'] = $cardata;
        $return['is_selectall'] = $is_selectall;
        $falg = msg(1, $return,'ok');
        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
    }

    public function delcar(){
        $mun =  db('goodscar')->where(['id'=>input('car_id')])->delete();
        if($mun){
            $falg = msg(-1, [],'ok');
            return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
            die;
        }
    }

    public function updata(){
        $mun =db('goodscar')->where('id',input('id'))->update(
                                                                [input('op')=>input('mun')]);
        if($mun){
            $falg = msg(-1, [],'ok');
            return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
            die;
        }
    }

    public function updatasalced(){
        $id = input('id');
        $is_select = db('goodscar')->where('id',$id)->field('is_select')->find();
        $value = 1;
        if ($is_select['is_select'] == 1){
            $value = 0;
        }
        $mun =db('goodscar')->where('id', $id)->update(['is_select'=>$value]);
        if($mun){
            $falg = msg(1, [],'ok');
            return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
            die;
        }
    }

    public function salcedall(){
        $unionid = input('unionid');
        $value = input('value') == 'true'?1:0;
        $mun =db('goodscar')->where('unionid', $unionid)->update(['is_select'=>$value]);
        if($mun){
            $falg = msg(1, [],'ok');
            return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
            die;
        }
    }

    /**
     * 确认购买页面
     * @return \think\response\Json
     */
    public function getAll(){
        $goodsid = input('goodsid');
        $total = 0;
        if(isset($goodsid) && !empty($goodsid)){
            //直接购买
            $data = db('goods')->where('id',$goodsid)->select();
            $shop_price =0;
            $shuxingid = 0;
            $shuxingname = '';
            if (input('shuxingid')){
                $shuxing = db('shuxing')->where('id',input('shuxingid'))->find();
                $shop_price = $shuxing['price'];
                $shuxingname = $shuxing['name'];
                $shuxingid = $shuxing['id'];
            }else{
                $shop_price = $data[0]['shop_price'];
            }


            foreach ($data as $k => $v){
                $data[$k]['price'] = $shop_price;
                $data[$k]['goodsmun'] = input('mun');
                $data[$k]['cname'] =$shuxingname;
                $data[$k]['shuxingid'] =$shuxingid;
                $total += input('mun') * $shop_price;
            }

        }else{
            //通过购物车购买
            $where['a.unionid'] =  input('unionid');
            $where['a.is_select'] =  1;

            $data = $data = db('goodscar')->alias('a')
                ->join('goods b','a.goods_id = b.id','LEFT')
                ->join('shuxing c','a.shuxing_id = c.id','LEFT')
                ->where($where)
                ->field('a.*,b.id as gid,b.goods_name,b.original_img,b.shop_price as price,c.price as cprice,c.name as cname,c.id as shuxing_id ')
                ->select();

            foreach ($data as $k => $v){
                $pirce = $v['price'];
                if (!empty($v['cprice'])){
                    $pirce = $v['cprice'];
                }
                $data[$k]['price'] = $pirce;
                $data[$k]['price'] = $pirce;
                $total += $v['goodsmun'] * $pirce;
            }
        }




       $memberid = db('member')->where('unionid',input('unionid'))->field('id')->find();
        $addr = db('addr')->alias('a')
            ->join('area b','a.sheng = b.id','LEFT')
            ->join('area c','a.shi = c.id','LEFT')
            ->join('area d','a.xian = d.id','LEFT')
            ->where('a.memberid',$memberid['id'])
            ->field('a.*,b.name as bname,c.name as cname,d.name as dname')
            ->select();

        $falgaddr =[]; //获取默认地址
        $addr1 = 1; //是否有地址
        if ($addr){
            foreach ($addr as $v){
                if ($v['isfag'] == 1){
                    $falgaddr = $v;
                }
            }
            if (!$falgaddr){
                $falgaddr = $addr[0];
            }
        }else{
            $addr1 = 0;
        }

        $return['data'] = $data;
        $return['total'] = $total;
        $return['falgaddr'] = $falgaddr;
        $return['addr1'] = $addr1;

        $falg = msg(1, $return,'ok');
        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
        die;

    }

    /**
     * 余额和提现说明
     * @return \think\response\Json
     */
    public function getyue(){
        $data = db('member')->where('id',input('id'))->field('yue,cz_yue')->find();
        $config = db('config')->where('id',1)->field('tixian_content')->find();
        $data['remark_s'] = $config['tixian_content'];
        $falg = msg(1, $data,'ok');
        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
    }
    //钱包列表
    public function getpaylist(){

//        $data = db('money')->where(['member_id'=>input('userid'),'type'=>3])->field('FROM_UNIXTIME(addtime,"%Y-%m-%d %H:%i:%s") as addtime,money')->select();
        $data = db('ticheng')->where(['userid'=>input('userid')])->field('FROM_UNIXTIME(addtime,"%Y-%m-%d %H:%i:%s") as addtime,money,IF(type =1,"+","-") as type,remark')->order('id desc')->select();
        $falg = msg(1, $data,'ok');
        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
        die;
    }

    /**
     * 提现
     * @return array
     */
    public function totixian(){
        $money = input('money');
        $data = db('config')->where('id',1)->find();
        $yue = db('member')->where('id',input('userid'))->find();
        if ($money > $data['money']){
            if ($money > $yue['yue']){
                return ['code'=>-1,'msg'=>"提现金额不能大于余额"];
            }
            $this->qianbao($money,'提现');
            $updata = $yue['yue']-$money;
            db('member')->where('id',input('userid'))->update(['yue'=>$updata]);//更新余额
            $arr['money'] =$money;
            $arr['userid'] = input('userid');
            $arr['addtime'] = time();
            $re = db('tixian')->insertGetId($arr);//添加提现信息
            if ($re){
                return json(['code'=>1,'msg'=>"提现成功!"]);
            }
        }else{

            return json(['code'=>-1,'msg'=>"提现金额不能低于{$data['money']}"]);
        }

    }
    //添加钱包体现记录
    public function qianbao($money,$remark){
        $ticheng = db('ticheng')->where('userid',input('userid'))->limit(1)->select();
        if (!empty($ticheng)){
            $after = $ticheng[0]['after'] ;
        }
        $qianbao['userid'] = input('userid');
        $qianbao['type'] = 2;
        $qianbao['remark'] = $remark;
        $qianbao['money'] = $money;
        $qianbao['addtime'] = time();
        $qianbao['after'] = $after - $money;//求改变后的量
        //添加钱包记录
        $ticheng = db('ticheng')->where('userid',input('userid'))->insertGetId($qianbao);
        if($ticheng){

            return true;
        }else{
            return false;
        }

    }
    public function question(){
        $data = db('config')->find(1);
        $falg = msg(1, $data['problem'],'ok');
        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
    }

    public function coupon(){
        $data = (new Coupon())->getlist();
        $falg = msg(1, $data,'ok');
        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
    }

    public function huoqucoupon(){
       $param = input();
       $re = db('coupon_h')->where(['user_id'=>$param['userid'], 'coupon_id'=>$param['id']])->find();
       if (!$re){
           $data = db('coupon')->where([ 'id'=>$param['id']])->find();
           if (!empty($data)){
               $res = db('coupon_h')->insertGetId([
                                'user_id'=>$param['userid'],
                                'coupon_id'=>$param['id'],
                                'addtime'=>time(),
                                'price'=>$data['price'],
                                'atime'=>$data['atime'],
                                'btime'=>$data['btime'],
                                'remark'=>$data['remark'],
                                'title'=>$data['title'],
                                'total_price'=>$data['total_price'],
                                ]);
               if ($res){
                   $falg = msg(1, [],'领取成功');
               }else{
                   $falg = msg(-1, [],'未知错误');
               }
           }else{
               $falg = msg(-1, [],'未知错误');
           }

       }else{
           $falg = msg(-1, [],'您已领取');
       }
        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
    }

    /**
     * 获取我的优惠券
     * @return \think\response\Json
     */
    public function getmycoupon(){
        $re = db('coupon_h')->where(['user_id'=>input('userid'), 'status'=>1])->select();
        $order = db('weixiou_h')->where('orderid',input('order_mun'))->select();
        $total = 0;
        foreach ($order as $v){
            $total += $v['price'] * $v['mun'];
        }
        $showModal= false;
        foreach ($re as $k =>$v){
            if ($v['btime'] <= time()){
                unset($re[$k]);
            }elseif($total < $v['total_price']){
                unset($re[$k]);
            }else{
                $re[$k]['is_select'] = false;
                $showModal = true;
            }

        }
        $dianzan = db('dianzan')->where(['userid'=> input('userid'), 'status' => 1])->count();
        $config = db('config')->where('id',1)->find();
        $data['coupon'] = $re;
        $data['showModal'] = $showModal;
        $data['dianzan'] = $dianzan*$config['money_mun'];
        $falg = msg(1, $data,'ok');
        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
    }

    /**
     * 首页优惠券图片
     * @return \think\response\Json
     */
    public function couponimg(){
        $data = db('config')->where('id',1)->field('url,is_show')->find();
        $falg = msg(1, $data,'ok');
        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
    }

    /**
     * 点赞
     * @return \think\response\Json
     */
    public function dianzan(){
        $userid = input('userid');
        $uid    = input('uid');
        $re = db('dianzan')->where(['userid' =>$userid, 'uid' => $uid])->find();
        if ($re){
            $falg = msg(-1, '','已经点赞过了');
        }else{
            $res = db('dianzan')->insertGetId(['userid' =>$userid, 'uid' => $uid]);
            if (!$res){
                $falg = msg(-1, '','已经点赞过了');
            }else{
                $falg = msg(1, '','ok');
            }

        }
        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
    }

    /**
     * 获取点赞数
     * @return \think\response\Json
     */
    public function getdianzan(){
        $userid = input('userid');
        $data =  db('dianzan')->where(['userid' =>$userid,])->field('count(id) as count')->count();
        $falg = msg(1, $data,'ok');
        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
    }

    public function xieyi(){
        $data = db('config')->where('id',1)->find();
        $falg = msg(1, $data,'ok');
        return json(['code'=>$falg['code'],'data'=>$falg['data'],'msg'=>$falg['msg']]);
    }





}